//http://localhost:8081/test?pid=pid01
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.WebServlet;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.XMLOutputter;

@WebServlet(urlPatterns={"/servlet/GuestBook"})
public class GuestBook extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private static final String _dataFilePath = "data.xml";
	private static final String _nameField = "name";
	private static final String _textField = "text";
	private static final String _timeField = "time";

	public GuestBook() {
		super();
	}

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {

		response.setContentType("text/html");
		PrintWriter html = response.getWriter();
		html.println("<html><head><title>Guest book</title></head><body><center>");

		try {
			html.println("<table border=1><tr><th>time</td><th>name</th><th>message</th></tr>");

			Document doc = loadXML(_dataFilePath);
			Iterator<Element> itr = doc.getRootElement().getChildren()
					.iterator();
			while (itr.hasNext()) {
				Element e = (Element) itr.next();
				String name = e.getChild(_nameField).getText();
				String message = e.getChild(_textField).getText();
				String time = e.getChild(_timeField).getText();
				html.println("<tr><td>" + time + "</td><td>" + name
						+ "</td><td>" + message + "</td></tr>");
			}

			html.println("</table>");

			String url = request.getRequestURI();
			html.println("<form method=post action=\""
					+ response.encodeURL(url) + "\">");
			html.println("enter entry name: ");
			html.println("<input name=name type=text><br>");
			html.println("enter the entry text: ");
			html.println("<input name=text type=text><br>");
			html.println("<input type=submit name=submit value=\"New entry\">");
			html.println("<br><br>");
			html.println("</form></center>");
		} catch (Exception ex) {
			// todo: report error
		}
		html.println("</body></html>");
	}

	private Document loadXML(String xmlPath) throws JDOMException, IOException {
		File file = new File(xmlPath);
		Document doc;
		if (file.exists()) {
			doc = new SAXBuilder().build(file);
		} else {
			doc = new Document();
			Element root = new Element("entries");
			doc.setRootElement(root);
		}
		return doc;
	}

	private Element buildEntry(String name, String text) {
		Element entry = new Element("entry");
		Element nameElement = new Element(_nameField);
		Element textElement = new Element(_textField);
		Element timeElement = new Element(_timeField);
		nameElement.setText(name);
		textElement.setText(text);
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		Date date = new Date();
		timeElement.setText(dateFormat.format(date));
		entry.addContent(nameElement);
		entry.addContent(textElement);
		entry.addContent(timeElement);
		return entry;
	}

	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {
			Document doc = loadXML(_dataFilePath);
			doc.getRootElement().addContent(
					buildEntry(request.getParameter("name"),
							request.getParameter("text")));

			XMLOutputter xout = new XMLOutputter();
			java.io.FileWriter writer = new java.io.FileWriter(_dataFilePath);
			xout.output(doc, writer);
			writer.flush();
			writer.close();

			doGet(request, response);
		} catch (Exception ex) {
			// todo: report error
		}
	}

}
